package com.huizu.project.service.impl;

import java.util.*;
import java.util.stream.LongStream;

import cn.hutool.core.collection.CollUtil;
import com.huizu.common.core.domain.AjaxResult;
import com.huizu.common.core.domain.entity.SysUser;
import com.huizu.common.exception.ServiceException;
import com.huizu.common.utils.DateUtils;
import com.huizu.common.utils.SecurityUtils;
import com.huizu.common.utils.dx.SecurityUtil;
import com.huizu.project.config.EnumConfig;
import com.huizu.project.domain.ProLd;
import com.huizu.project.domain.ProNotice;
import com.huizu.project.domain.ProUser;
import com.huizu.project.mapper.*;
import com.huizu.project.service.ISysUserVoService;
import com.huizu.system.mapper.SysUserMapper;
import com.huizu.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huizu.project.domain.ProUserTer;
import com.huizu.project.service.IProUserTerService;

/**
 * 教师用户Service业务层处理
 * 
 * @author zhangmx
 * @date 2024-05-25
 */
@Service
public class ProUserTerServiceImpl implements IProUserTerService 
{
    @Autowired
    private ProUserTerMapper proUserTerMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ProLdMapper proLdMapper;

    @Autowired
    private ProLdgyMapper proLdgyMapper;

    @Autowired
    private ProLdcgMapper proLdcgMapper;

    @Autowired
    private ProLdzjMapper proLdzjMapper;

    @Autowired
    private ProUserDcMapper proUserDcMapperl;

    @Autowired
    private ProNoticeMapper proNoticeMapper;

    @Autowired
    SysUserMapper sysUserMapper;




    /**
     * 查询教师用户
     * 
     * @param userId 教师用户主键
     * @return 教师用户
     */
    @Override
    public SysUser selectProUserTerByUserId(String userId)
    {
        return sysUserMapper.selectUserById(Long.parseLong(userId));
    }

    /**
     * 查询教师用户列表
     * 
     * @param proUserTer 教师用户
     * @return 教师用户
     */
    @Override
    public List<ProUserTer> selectProUserTerList(ProUserTer proUserTer)
    {
        return proUserTerMapper.selectProUserTerList(proUserTer);
    }

    /**
     * 新增教师用户
     * 
     * @param proUserTer 教师用户
     * @return 结果
     */
    @Override
    public int insertProUserTer(ProUserTer proUserTer)
    {
        ProUserTer proUser1 = proUserTerMapper.selectProUserTerByUserId(proUserTer.getJsNumber());
        if (proUser1!=null)
            throw new ServiceException("职工号已重复："+proUser1.getJsNumber());
        proUserTer.setUserId(proUserTer.getJsNumber());
        String passwordMd5 = SecurityUtil.md5enc("admin123");//默认密码
        proUserTer.setPassword(passwordMd5);
        proUserTer.setCreateTime(DateUtils.getNowDate());

        SysUser sysUser = new SysUser();
        sysUser.setNickName(proUserTer.getName());
        sysUser.setUserName(proUserTer.getJsNumber());
        sysUser.setJsNumber(proUserTer.getJsNumber());
        sysUser.setPassword(SecurityUtils.encryptPassword("admin123"));//默认密码
        sysUser.setPhonenumber(proUserTer.getPhone());
        Long[] roles = new Long[]{
                EnumConfig.Role.js
        };
        sysUser.setRoleIds(roles);
        sysUser.setDeptId(Long.parseLong(proUserTer.getXyId()));
        sysUser.setBusId(proUserTer.getJsNumber());
        sysUserService.insertUser(sysUser);


        return proUserTerMapper.insertProUserTer(proUserTer);
    }

    /**
     * 重置密码
     *
     * @param proUser 用户管理
     * @return 结果
     *2024-8-17 修改：sys_user表同步修改密码
     */
    public int resetPassword(ProUserTer proUser){
        String passwordSysUser = proUser.getPassword();//sys_user 密码
        String passwordMd5 = SecurityUtil.md5enc(proUser.getPassword());//pro_user_ter 密码
//        String userId = UniqueStringGenerator.generateUniqueString();
        proUser.setPassword(passwordMd5);
        SysUser sysUser = new SysUser();
        sysUser = sysUserService.selectUserByUserName(proUser.getUserId());
        sysUser.setPassword(SecurityUtils.encryptPassword(passwordSysUser));
        sysUserMapper.updateUser(sysUser);
        return proUserTerMapper.updateProUserTer(proUser);
    }

    public AjaxResult updatePassword2(ProUserTer proUserPram){
        if (proUserPram.getPassword()==null||"".equals(proUserPram.getPassword()))
            throw new ServiceException("请输入旧密码");
        if (proUserPram.getPasswordNew()==null||"".equals(proUserPram.getPasswordNew()))
            throw new ServiceException("请输入新密码");

        SysUser user = sysUserMapper.selectUserById(Long.valueOf(proUserPram.getUserId()));
        if (user==null)
            return AjaxResult.error("用户异常");
        boolean isPassword = SecurityUtil.authenticatePassword(user.getUnPassword(), proUserPram.getPassword());
        if (!isPassword)
            return AjaxResult.error("原密码错误");

        user.setPassword(SecurityUtils.encryptPassword(proUserPram.getPasswordNew()));
        user.setUnPassword(SecurityUtil.md5enc(proUserPram.getPasswordNew()));
        sysUserMapper.updateUser(user);
        return AjaxResult.success("修改成功");
    }

    /**
     * 修改教师用户
     * 
     * @param proUserTer 教师用户
     * @return 结果
     */
    // modify by pjl 2024-08-29 添加教工号是否重复校验
    @Override
    public int updateProUserTer(ProUserTer proUserTer)
    {
        // 根据教工号查询教工信息
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(proUserTer,sysUser);
        sysUser.setJsNumber(proUserTer.getJsNumber());
        sysUser.setUserId(Long.parseLong(proUserTer.getUserId()));
        List<SysUser> users = sysUserService.selectUserList(sysUser);
        if (CollUtil.isNotEmpty(users)) {
            throw new ServiceException("对不起，您输入的教工号重复[" + proUserTer.getJsNumber() + "]");
        }

        return sysUserService.updateUser(sysUser);
    }

    /**
     * 批量删除教师用户
     * 
     * @param userIds 需要删除的教师用户主键
     * @return 结果
     */
    @Override
    public int deleteProUserTerByUserIds(String[] userIds)
    {
        Long[] ids = new Long[userIds.length];
        for (int i = 0; i < userIds.length; i++) {
            ids[i]=Long.valueOf(userIds[i]);
        }
        return sysUserService.deleteUserByIds(ids);
    }

    /**
     * 删除教师用户信息
     * 
     * @param userId 教师用户主键
     * @return 结果
     */
    @Override
    public int deleteProUserTerByUserId(String userId)
    {
        return sysUserService.deleteUserById(Long.valueOf(userId));
    }

    public AjaxResult listMessage(Map<String, Object> map){
        List<Map<String,Object>> respList = new ArrayList<>();
        String userId = String.valueOf(map.get("userId"));

        ProLd proLdPram = new ProLd();
        proLdPram.setBeUserId(userId);
        proLdPram.setUserId(userId);
        proLdPram.setStatus("1");
        List<ProLd> proLds = proLdMapper.selectProLdList(proLdPram);
        long count = proLds.stream().filter(l -> l.getXxStatus() == 0).count();

        ProNotice proNoticePram = new ProNotice();
        proNoticePram.setBeUserId(userId);
        List<ProNotice> proNotices = proNoticeMapper.selectProNoticeList(proNoticePram);
        long count2 = proNotices.stream().filter(l -> l.getXxStatus() == 0).count();

        Map<String,Object> objectMap = new HashMap<>();
        objectMap.put("name","待办事项");
        objectMap.put("type","1");
        objectMap.put("count",count);

        Map<String,Object> objectMap2 = new HashMap<>();
        objectMap2.put("name","通知公告");
        objectMap2.put("type","2");
        objectMap2.put("count",count2);

        Map<String,Object> objectMap3 = new HashMap<>();
        objectMap3.put("name","系统消息");
        objectMap3.put("type","3");
        objectMap3.put("count",count2);

        respList.add(objectMap);
        respList.add(objectMap2);
        respList.add(objectMap3);
        return AjaxResult.success(respList);
    }

    @Override
    public AjaxResult relieveBinding(SysUser sysUser) {
        sysUserMapper.relieveBinding(sysUser);
        return AjaxResult.success("解除绑定成功");
    }
}
